﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Web;

namespace Lot.WebClient
{
    internal class RequestConfiguration:ClientConfiguration
    {
        private String url { get; set; }
        public String Url
        {
            get { return GetUrl(); }
            set { SetUrl(value); }
        }
        public NameValueCollection QueryString { get; set; }
        public HttpMethods HttpMethod { get; set; }
        public MimeType Accept { get; set; }
        public String AcceptLanguage { get; set; }
        public String AcceptCharset { get; set; }
        public String Referer { get; set; }
        public String Origin { get; set; }
        public String Host { get; set; }        
        public IPostData PostData { get; set; }
        public NameValueCollection CookiesToSet { get; set; }

        public RequestConfiguration(ClientConfiguration clientConfiguration = null)
        {
            var client = clientConfiguration??new ClientConfiguration();

            this.PersistCookies = client.PersistCookies;
            this.AutoFollowRedirects = client.AutoFollowRedirects;
            this.Timeout = client.Timeout;
            this.UserAgent = client.UserAgent;
            this.EnableCompression = client.EnableCompression;
            this.Proxy = client.Proxy;
            this.TryKeepAlive = client.TryKeepAlive;


            //Defaults
            this.QueryString = new NameValueCollection();
            this.Accept = MimeType.Anything;
            this.CookiesToSet = new NameValueCollection();
            
        }

        private void SetUrl(string url)
        {
            var uri = new Uri(url);
            if (uri.Query.Length > 0)
            {
                QueryString = HttpUtility.ParseQueryString(uri.Query);
                this.url = url.Split('?')[0];
            }
            else
            {
                this.url = url;
            }           
            
        }

        private string GetUrl()
        {
            if (QueryString.Count > 0)
            {
                return String.Format("{0}?{1}", url, QueryString.ToString());
            }
            else
            {
                return url;
            }
            

        }
    }

    public enum HttpMethods
    {
        GET,
        POST,
        PUT,
        HEAD,
        DELETE

    }
}
